package com.share.two.mail.util;

import java.io.File;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

/**
 *邮件发送帮助类，该类主要是对spring集成邮件的工具类做了相应的改写。
 */
@Service
public class EmailSendHelper {

	private static final Logger log = Logger.getLogger("runLog");
	@Autowired
	private JavaMailSenderImpl mailSender;
	@Resource
	private ThreadPoolTaskExecutor threadPool;

	/**
	 * 
	 * <p>Title: send </p>
	 * <p>Description: 发送邮件方法继承spring的邮件工具类 </p>
	 * @param from
	 * @param to
	 * @param cs 抄送
	 * @param subject 主题
	 * @param text 内容
	 * @param files 附件list
	 */
	public void send(final String[] to, final String[] cs, final String subject,
			final String text, final String... files) {
		//mailSender.send(builderMimeMessage(to, cs, subject, text, files));
		threadPool.execute(new Runnable() {
			@Override
			public void run() {
				mailSender.send(builderMimeMessage(to, cs, subject, text, files));
			}
		});
	}

	/**
	 * 发送多个邮件
	 * @param mimeMessages 
	 */
	public void send(MimeMessage[] mimeMessages) {
		mailSender.send(mimeMessages);
	}

	/**
	 * 构建邮件massage
	 * 
	 * @param from
	 * @param to
	 * @param cs
	 * @param subject
	 * @param text
	 * @param files
	 * @return
	 */
	public MimeMessage builderMimeMessage(String[] to,
			String[] cs, String subject, String text, String... files) {
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = null;
		try {
			helper = new MimeMessageHelper(message, true, "utf-8");
			helper.setFrom(mailSender.getUsername());
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(text);
			helper.setCc(cs);
			log.info("MimeMessage 构造成功");
		} catch (MessagingException e) {
			log.error("MimeMessage 构造失败",e);
		}
		
		if (files == null) {
			return message;
		}

		for (final String path : files) {
			FileSystemResource file = new FileSystemResource(new File(path));
			try {
				helper.addAttachment(MimeUtility.encodeWord(file.getFilename()), file);
				log.info("成功添加附件：  " + path);
//			} catch (UnsupportedEncodingException e) {
//				log.error(e.getMessage(),e);
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
		}
		return message;
		
	}


}
